package com.han.fu.api.common.handle;

import com.alibaba.fastjson.JSON;
import com.han.fu.api.common.model.ResponseVo;
import com.han.fu.api.common.enums.SecurityEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限不足处理
 *
 * @author: star
 * @date: 2021-07-31
 */
@Component
@Slf4j
public class PermissionDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        // 登陆状态下，权限不足执行该方法
        log.warn("{}-权限不足：{}",request.getServletPath(), e.getMessage());
        response.setStatus(SecurityEnum.PERMISSION_DENIED.getCode());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        ResponseVo<String> result = new ResponseVo<>();
        SecurityEnum.setResponseVo(result, SecurityEnum.PERMISSION_DENIED);
        String body = JSON.toJSONString(result);
        printWriter.write(body);
        printWriter.flush();
    }
}
